package com.zhugang.week05;


/**
 * @program algorithms
 * @description: bSearchCycleEquals
 * @author: chanzhugang
 * @create: 2022/07/04 20:40
 */
public class BSearchCycleEquals {

    public static void main(String[] args) {
        BSearchCycleEquals bSearchCycleEquals = new BSearchCycleEquals();
        int[] a = new int[]{7, 9, 11, 15, 1, 3, 5, 6};
        int index = bSearchCycleEquals.bSearchCycleEquals(a, a.length, 3);
        System.out.println(index);
    }

    /**
     * 循环有序数组中查找给定值(下标)
     * [7,9,10,11,15, 1,3,5,6]
     * 举例画图理解
     *
     * @param a
     * @param n
     * @param target
     * @return
     */
    public int bSearchCycleEquals(int[] a, int n, int target) {
        // 标准二分改造
        int low = 0;
        int high = n - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (a[mid] == target) {
                return mid;
            } else if (a[low] <= a[mid]) {
                // 左边是有序数组
                if (target >= a[low] && target < a[mid]) {
                    high = mid - 1;
                } else {
                    low = mid + 1;
                }
            } else {
                // 右边是有序数组
                if (target > a[mid] && target <= a[high]) {
                    low = mid + 1;
                } else {
                    high = mid - 1;
                }
            }
        }
        return -1;
    }
}